'use strict';

const crypto = require('crypto');
// 通过 require 引入 vk 实例
let vk = require('vk-unicloud');
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});
const db = uniCloud.database();
const _ = db.command
exports.main = async (event, context) => {

	// let user_order_success = true;
	//event为客户端上传的参数---------订单信息
	console.log('event : ', event)

	let signature = event.queryStringParameters.signature
	let echostr = event.queryStringParameters.echostr
	let timestamp = event.queryStringParameters.timestamp
	let nonce = event.queryStringParameters.nonce

	// 此处的token 不要改  固定这样
	let token = "f4c680873160335bd83d4692d0d55ba3"

	const tmpArr = [token, timestamp, nonce];
	tmpArr.sort();
	const tmpStr = tmpArr.join('');
	const tmpStrSha1 = crypto.createHash('sha1').update(tmpStr).digest('hex');
	// 校验成功，返回给微信平台
	if (tmpStrSha1 === signature) {

		// 微信开发平台服务推送配置成功之后注释掉这段代码
		// return echostr;

		let body = JSON.parse(event.body)

		// 订单号
		let out_trade_no = body.OutTradeNo
		let openid = body.OpenId

		let total_fee = 0 // 以分为单位，Quantity是实付金额，单位分
		try {
			//    支付比例为 1 : 1 时 此处 需要 * 100
			total_fee = body.CoinInfo.Quantity
		} catch (err) {
			return 'success'
		}

		let orderinfo = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()

		if (orderinfo.data[0].pay_status == 1) {
			return 'success';
		}
		// let resu = reso.rows[0]
		// console.log("resu", resu);
		let transaction_id = orderinfo.data[0].transaction_id
		let log_No = orderinfo.data[0].log_No
		let trade_no = orderinfo.data[0].trade_no
		let os_name = orderinfo.data[0].os_name
		let subject = orderinfo.data[0].subject
		let user_id = orderinfo.data[0].user_id
		let bean_number = orderinfo.data[0].bean
		let _add_time = new Date().getTime()
		let _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
		let data = {
			transaction_id,
			log_No,
			trade_no,
			os_name,
			subject,
			user_id,
			bean_number,
			_add_time,
			_add_time_str
		}
		if (!out_trade_no || !total_fee) {
			// user_order_success = false;
			return "success";
		}

		//判断订单金额和实付金额是否一致
		if (orderinfo.data[0].recharge_amount != total_fee) {
			//添加金豆收支明细
			const add_error = await db.collection('vk-test').add({
				user_id: user_id,
				orderinfo: orderinfo.data[0],
				remark: "实付金额和订单金额不一致，疑似抓包",
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
			console.log("订单金额和实付金额不一致");
			return res;
		}

		let recharge_all = await vk.baseDao.count({
			dbName: "a_recharge", // 表名
			whereJson: { // 条件

				pay_status: 1,
				user_id: user_id,
			}
		});

		//修改充值记录订单，状态为已支付，并记录实付金额，微信支付订单号等
		const update_order = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).update({
			recharge_all: recharge_all + 1,
			openid: openid,
			shifu_amount: total_fee,
			transaction_id: transaction_id,
			pay_status: 1,
			_add_time: _add_time,
			_add_time_str: _add_time_str,
			finish_time: new Date().getTime(),
			log_No: log_No,
			trade_no: trade_no,
			os_name: os_name,
		})

		console.log('修改订单信息');

		if (subject == "自定义会员") {
			let addtime = 0;
			const onedaytime = 86400000 //1天
			const onehourtime = 3600000 //1小时

			if (orderinfo.data[0].days) {
				addtime = onedaytime * orderinfo.data[0].days
			}
			if (orderinfo.data[0].hour) {
				addtime = onehourtime * orderinfo.data[0].hour
			}
			//先查询用户信息，是否已是会员
			let getres = await db.collection('uni-id-users').doc(user_id).field({
				plus_expire_time: true
			}).get()


			var nowtime = new Date().getTime()
			const plus_expire = getres.data[0].plus_expire_time
			if (plus_expire * 1 < nowtime * 1) {
				let new_expire_time = nowtime * 1 + addtime;
				//如果会员已到期，会员时间就是当前时间+addtime
				let updateVip = await db.collection('uni-id-users').doc(user_id).update({
					is_paid: true, //记录用户已支付
					plus_type: 1,
					plus_expire_time: new_expire_time
				})
			} else {
				console.log("修改用户会员到期时间");
				let new_expire_time2 = plus_expire * 1 + addtime
				//如果会员没有到期，会员时间就是到期时间+addtime
				let updateVip2 = await db.collection('uni-id-users').doc(user_id).update({
					is_paid: true, //记录用户已支付
					plus_expire_time: new_expire_time2
				})
			}
		}

		if (subject == "充值金豆") {
			console.log("充值成功！", openid);
			//如果修改成功，给用户增加金豆数量
			//此方法腾讯云和阿里云都支持
			let newInfo = await vk.baseDao.updateAndReturn({
				dbName: "uni-id-users",
				whereJson: {
					_id: user_id
				},
				dataJson: {
					is_paid: true,
					had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
					balance: _.inc(bean_number)
				}
			});

			console.log('添加金豆数量');


			//添加金豆收支明细
			const add_jindou = await db.collection('a_jindou_detail').add({
				user_id: user_id,
				nickname: newInfo.nickname || "未绑定",
				change_num: bean_number, //增加的金豆数量
				changed_num: newInfo.balance, //支付后金豆余额
				change_reason: "支付" + total_fee + "分钱充值" + bean_number + "金豆",
				type: "income", //类型：expend:支出,income:收入。
				appid: newInfo.appid || "",
				appname: newInfo.appname || "",
				_add_time: _add_time,
				_add_time_str: _add_time_str,
				os_name: os_name,
				finish_time: new Date().getTime()
			})

			console.log('添加金豆收支明细');
		} else if (subject == "单剧会员") {
			let newInfo = await vk.baseDao.updateAndReturn({
				dbName: "uni-id-users",
				whereJson: {
					_id: user_id
				},
				dataJson: {
					is_paid: true,
					had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
				}
			});
			//添加单剧会员
			let add_djhy = await db.collection('a_djhy').add({
				user_id: user_id,
				nickname: orderinfo.data[0].nickname || "未绑定",
				tv_name: orderinfo.data[0].tv_name,
				tv_id: orderinfo.data[0].tv_id,
				appid: orderinfo.data[0].appid || "",
				appname: orderinfo.data[0].appname || "",
				_add_time: data._add_time,
				_add_time_str: data._add_time_str
			})
		}
		if (data.subject == "开通会员" || data.subject == "年度会员" || data.subject == "季度会员" || data.subject ==
			"月度会员") {
			let addtime = 0;
			//【开通会员】这个类型是为了兼容老版本的年费会员
			if (subject == "开通会员") {
				addtime = 31536000000 //365天
			}
			if (subject == "年度会员") {
				addtime = 31536000000 //365天
			}
			if (subject == "季度会员") {
				addtime = 7776000000 //90天
			}
			if (subject == "月度会员") {
				addtime = 2592000000 //30天
			}
			//先查询用户信息，是否已是会员
			let getres = await db.collection('uni-id-users').doc(user_id).field({
				plus_expire_time: true
			}).get()

			var nowtime = new Date().getTime()
			const plus_expire = getres.data[0].plus_expire_time
			if (plus_expire * 1 < nowtime * 1) {
				let new_expire_time = nowtime * 1 + addtime;
				//如果会员已到期，会员时间就是当前时间+addtime
				let updateVip = await db.collection('uni-id-users').doc(user_id).update({
					is_paid: true,
					plus_type: 1,
					plus_expire_time: new_expire_time
				})
			} else {
				console.log("修改用户会员到期时间");
				let new_expire_time2 = plus_expire * 1 + addtime
				//如果会员没有到期，会员时间就是到期时间+addtime
				let updateVip2 = await db.collection('uni-id-users').doc(user_id).update({
					plus_expire_time: new_expire_time2
				})
			}
		}


		async function addvktest(tips) {
			let addvktest = await db.collection('callback_log').add({
				tips: tips,
				out_trade_no: out_trade_no,
				total_fee: total_fee,
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
		}

		let num_recharge_one = await vk.baseDao.count({
			dbName: "a_recharge", // 表名
			whereJson: { // 条件
				user_id: user_id,
				pay_status: 1
			}
		});
		if (num_recharge_one == 1) {
			// 返回被修改的记录条数
			let num = await vk.baseDao.update({
				dbName: "a_recharge", // 表名
				whereJson: { // 条件
					out_trade_no: out_trade_no
				},
				dataJson: { // 需要修改的数据
					is_first: true
				}
			});
		}


		//======获取回传比例开始======
		let percent = null
		let tfurlpercent = await db.collection('a_config').where({
			name: "RebackPercent",
			tfid: orderinfo.data[0].tfid //添加这条数据的代理商ID
		}).get()


		if (tfurlpercent.data.length != 0) {
			percent = tfurlpercent
		} else {
			percent = await db.collection('a_config').where({
				name: "RebackPercent",
				user_id: orderinfo.data[0].invite_code || 0 //添加这条数据的代理商ID
			}).get()
		}

		let Radios = 0;
		if (percent.data[0]) {
			console.log("存在代理商比例数据", percent);
			if (orderinfo.data[0].tg_pt == "douyin") {
				Radios = percent.data[0].douyinRadio * 1 || 0;
			}
			if (orderinfo.data[0].tg_pt == "baidu") {
				Radios = percent.data[0].baiduRadio * 1 || 0;
			}
			if (orderinfo.data[0].tg_pt == "kuaishou") {
				Radios = percent.data[0].kuaishouRadio * 1 || 0;
			}
			if (orderinfo.data[0].tg_pt == "tengxun") {
				Radios = percent.data[0].tengxunRadio * 1 || 0;
			}

		} else {
			console.log("不存在代理商比例数据");
		}

		//判断是否循环回传
		//循环回传模式
		if (Radios === 1) {
			await vk.callFunction({
				name: "hedian",
				url: 'client/user/pub/proportional_callabck',
				title: '请求中...',
				data: {
					out_trade_no: out_trade_no, //充值订单号
					total_fee: total_fee, //支付金额
					_add_time: data._add_time,
					_add_time_str: data._add_time_str,
					percent: percent
				},
			});
			await addvktest("进行了比例回传");
		} else {
			//百分比回传模式
			// 云函数内调用其他云函数或云对象内的函数,进行付费数据回传。
			let callRes = await vk.callFunction({
				name: "hedian",
				url: 'client/user/pub/callback',
				data: {
					out_trade_no: out_trade_no, //充值订单号
					total_fee: total_fee, //支付金额
					_add_time: data._add_time,
					_add_time_str: data._add_time_str
				},
			});
			console.log("百分比回传")
			await addvktest("进行了概率回传");
			return "success";
		}





		return "success";
	} else {
		console.log("签名不符，程序结束");
		return false;
	}



};